#include<conio.h>
#include<graphics.h>
#include<stdio.h>
#define N 30

int main()
{
	int range = 100;//确定数组值范围

	int graphheight = 600;
	int graphwidth = 1000;
	initgraph(graphwidth, graphheight);//规定窗口大小
	setbkcolor(RGB(237, 237, 237));
	cleardevice();

	int singleheight = graphheight / range;//规定矩形单位高度
	int recwidth = graphwidth / N;//规定矩形宽度

	
	int i, mid, temp, maxnumber=0, max = 0;
	int arr[N];

	for (i = 0;i < N;i++)
	{
		arr[i] = rand() % range;//对数组动态赋值(<100)
		int height = arr[i] * singleheight;//计算矩形高度
		setfillcolor(RGB(218, 42, 56));
		fillrectangle(i * recwidth, graphheight - height, (i + 1) * recwidth, graphheight);//绘制矩形
		Sleep(50);
	}
	//BeginBatchDraw();
	for (i = 0;i < N;i++)
	{
		max = -1;
		for (mid = i;mid < N;mid++)
		{
			if (mid - 1 != maxnumber)
			{
				int height = arr[mid - 1] * singleheight;//计算矩形高度
				setfillcolor(RGB(218, 42, 56));
				fillrectangle((mid - 1) * recwidth, graphheight - height, mid * recwidth, graphheight);//绘制矩形
			}
			int height = arr[mid] * singleheight;//计算矩形高度
			setfillcolor(RGB(254, 169, 0));//
			fillrectangle(mid * recwidth, graphheight - height, (mid + 1) * recwidth, graphheight);//绘制矩形
			Sleep(300);

			height = arr[i] * singleheight;//计算矩形高度
			setfillcolor(RGB(13, 128, 0));
			fillrectangle(i * recwidth, graphheight - height, (i + 1) * recwidth, graphheight);
			height = arr[i] * singleheight;//计算矩形高度
			
			if (arr[mid] > max)
			{
				setfillcolor(RGB(218, 42, 56));//去除旧最大数颜色
				int height = arr[maxnumber] * singleheight;//计算矩形高度
				fillrectangle(maxnumber * recwidth, graphheight - height, (maxnumber + 1) * recwidth, graphheight);
				max = arr[mid];//目前最大值
				maxnumber = mid;//目前最大数的下标
				setfillcolor(RGB(13, 128, 0));//变色现有最大数
				height = arr[maxnumber] * singleheight;//计算矩形高度
				fillrectangle(maxnumber * recwidth, graphheight - height, (maxnumber + 1) * recwidth, graphheight);
			}
			Sleep(50);
			//cleardevice();
		}
		
		temp = arr[i];
		arr[i] = arr[maxnumber];
		arr[maxnumber] = temp;

		cleardevice();
		for (mid = 0;mid < N;mid++)
		{
			setfillcolor(RGB(218, 42, 56));
			int height = arr[mid] * singleheight;//计算矩形高度
			fillrectangle(mid * recwidth, graphheight - height, (mid + 1) * recwidth, graphheight);//绘制矩形
		}
		//FlushBatchDraw();
		Sleep(50);	
	}
	_getch();
	closegraph();
	return 0;
}